package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.GradeLayer;
import com.xmy.cultivate.service.IGradeLayerService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 班级分层设置 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-08-26
 */
@RestController
@RequestMapping("/api/gradeLayer")
public class GradeLayerController {
    @Autowired
    IGradeLayerService iGradeLayerService;

    @GetMapping("")
    @ApiOperation("查询班级分层设置")
    public Result searchGradeLayer(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<GradeLayer> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String classTypeId = (String) reMap.get("classTypeId");
        String subjectsId = (String) reMap.get("subjectsId");
        String yearClassId = (String) reMap.get("yearClassId");
        String lessonType = (String) reMap.get("lessonType");
        String startScore = (String) reMap.get("startScore");
        String endScore = (String) reMap.get("endScore");

        QueryWrapper<GradeLayer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(classTypeId), "class_type_id", classTypeId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);

        String[] yearClassIdStr = yearClassId.split(","); // 拆分成数组
        StringBuilder condition = new StringBuilder();
        for (int i = 0; i < yearClassIdStr.length; i++) {
            if (i > 0) {
                condition.append(" OR ");
            }
            condition.append("FIND_IN_SET(").append(yearClassIdStr[i]).append(", year_class_id_str)");
        }
        if (StringUtils.isNotBlank(yearClassId)) {
            queryWrapper.apply("(" + condition + ")");
        }

        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.ge(StringUtils.isNotBlank(startScore), "start_score", startScore);
        queryWrapper.le(StringUtils.isNotBlank(endScore), "end_score", endScore);

        iGradeLayerService.page(iPage, queryWrapper);

        return new Result(Code.GET_OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    @PostMapping("")
    @ApiOperation("添加班级分层设置")
    public Result createGradeLayer(@RequestBody GradeLayer gradeLayer) {
        StringBuffer reminderSb = new StringBuffer();
        StringBuffer yearClassIdSb = new StringBuffer();
        StringBuffer yearClassNameSb = new StringBuffer();

        for (Integer yearClassId : gradeLayer.getYearClassIdList()) {
            QueryWrapper<GradeLayer> wrapper = new QueryWrapper<>();
            wrapper.eq("year_part", gradeLayer.getYearPart());
            wrapper.eq("quarter_num", gradeLayer.getQuarterNum());
            wrapper.eq("class_type_id", gradeLayer.getClassTypeId());
            wrapper.eq("subjects_id", gradeLayer.getSubjectsId());
            wrapper.eq("lesson_type", gradeLayer.getLessonType());
            wrapper.apply("FIND_IN_SET({0}, year_class_id_str)", yearClassId);

            Long count = iGradeLayerService.count(wrapper);
            if (count > 0) {
                reminderSb.append(CommonUtil.getYearClassNameForId(yearClassId));
                reminderSb.append(",");
            } else {
                if (StringUtils.isNotBlank(String.valueOf(yearClassIdSb))) {
                    yearClassIdSb.append(",");
                }
                yearClassIdSb.append(yearClassId);

                if (StringUtils.isNotBlank(String.valueOf(yearClassNameSb))) {
                    yearClassNameSb.append(",");
                }
                yearClassNameSb.append(CommonUtil.getYearClassNameForId(yearClassId));
            }
        }

        String reminderStr = "";
        if (!reminderSb.toString().isEmpty()) {
            reminderStr = reminderSb.toString();
            reminderStr = reminderStr.substring(0, reminderStr.length() - 1);
            reminderStr = "【" + reminderStr + "】已添加过，不可重复添加";
            return new Result(Code.ERROR, null, reminderStr);
        }

        if (StringUtils.isBlank(String.valueOf(yearClassIdSb)) && !reminderSb.toString().isEmpty()) {
            return new Result(Code.ERROR, null, reminderStr);
        }

        GradeLayer layer = new GradeLayer();
        layer.setYearPart(gradeLayer.getYearPart());
        layer.setQuarterNum(gradeLayer.getQuarterNum());
        layer.setClassTypeId(gradeLayer.getClassTypeId());
        layer.setStartScore(gradeLayer.getStartScore());
        layer.setEndScore(gradeLayer.getEndScore());
        layer.setSubjectsId(gradeLayer.getSubjectsId());
        layer.setYearClassIdStr(String.valueOf(yearClassIdSb));
        layer.setYearClassNameStr(String.valueOf(yearClassNameSb));
        layer.setLessonType(gradeLayer.getLessonType());
        layer.setGradeSection(gradeLayer.getGradeSection());
        iGradeLayerService.save(layer);

        if (!reminderSb.toString().isEmpty()) {
            return new Result(Code.ERROR, null, reminderStr);
        }

        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @PutMapping("")
    @ApiOperation("修改班级分层设置")
    public Result updateGradeLayer(@RequestBody GradeLayer gradeLayer) {
        StringBuffer reminderSb = new StringBuffer();
        StringBuffer yearClassIdSb = new StringBuffer();
        StringBuffer yearClassNameSb = new StringBuffer();

        for (Integer yearClassId : gradeLayer.getYearClassIdList()) {
            QueryWrapper<GradeLayer> wrapper = new QueryWrapper<>();
            wrapper.eq("year_part", gradeLayer.getYearPart());
            wrapper.eq("quarter_num", gradeLayer.getQuarterNum());
            wrapper.eq("class_type_id", gradeLayer.getClassTypeId());
            wrapper.eq("subjects_id", gradeLayer.getSubjectsId());
            wrapper.eq("lesson_type", gradeLayer.getLessonType());
            wrapper.apply("FIND_IN_SET({0}, year_class_id_str)", yearClassId);
            wrapper.ne("id", gradeLayer.getId()); // 排除当前记录

            Long count = iGradeLayerService.count(wrapper);
            if (count > 0) {
                reminderSb.append(CommonUtil.getYearClassNameForId(yearClassId));
                reminderSb.append(",");
            } else {
                if (StringUtils.isNotBlank(String.valueOf(yearClassIdSb))) {
                    yearClassIdSb.append(",");
                }
                yearClassIdSb.append(yearClassId);

                if (StringUtils.isNotBlank(String.valueOf(yearClassNameSb))) {
                    yearClassNameSb.append(",");
                }
                yearClassNameSb.append(CommonUtil.getYearClassNameForId(yearClassId));
            }
        }

        String reminderStr = "";
        if (!reminderSb.toString().isEmpty()) {
            reminderStr = reminderSb.toString();
            reminderStr = reminderStr.substring(0, reminderStr.length() - 1);
            reminderStr = "【" + reminderStr + "】已添加过，不可重复添加";
            return new Result(Code.ERROR, null, reminderStr);
        }

        if (StringUtils.isBlank(String.valueOf(yearClassIdSb)) && !reminderSb.toString().isEmpty()) {
            return new Result(Code.ERROR, null, reminderStr);
        }

        GradeLayer layer = new GradeLayer();
        layer.setId(gradeLayer.getId());
        layer.setYearPart(gradeLayer.getYearPart());
        layer.setQuarterNum(gradeLayer.getQuarterNum());
        layer.setClassTypeId(gradeLayer.getClassTypeId());
        layer.setStartScore(gradeLayer.getStartScore());
        layer.setEndScore(gradeLayer.getEndScore());
        layer.setSubjectsId(gradeLayer.getSubjectsId());
        layer.setYearClassIdStr(String.valueOf(yearClassIdSb));
        layer.setYearClassNameStr(String.valueOf(yearClassNameSb));
        layer.setLessonType(gradeLayer.getLessonType());
        layer.setGradeSection(gradeLayer.getGradeSection());
        iGradeLayerService.updateById(layer);

        if (!reminderSb.toString().isEmpty()) {
            return new Result(Code.ERROR, null, reminderStr);
        }

        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @DeleteMapping("")
    @ApiOperation("删除班级分层设置")
    public Result deleteGradeLayer(@RequestParam(value = "id") String id) {
        iGradeLayerService.removeById(id);
        return new Result(Code.DELETE_OK, null, Code.DELETE_OK_MSG);
    }
}
